package org.filetransfer.file_transfer_java_backend.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.filetransfer.file_transfer_java_backend.config.RequireAuth;
import org.filetransfer.file_transfer_java_backend.entity.User;
import org.filetransfer.file_transfer_java_backend.model.ApiResponse;
import org.filetransfer.file_transfer_java_backend.service.AvatarService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Map;

@RestController
@RequestMapping("/api/avatar")
@RequiredArgsConstructor
@Slf4j
public class AvatarController {
    
    private final AvatarService avatarService;      /**
     * 上传头像
     */
    @RequireAuth
    @PostMapping("/upload")
    @Operation(summary = "上传用户头像", description = "上传并处理用户头像，自动调整大小")
    @SecurityRequirement(name = "Bearer Authentication")
    public ResponseEntity<ApiResponse<Map<String, String>>> uploadAvatar(
            @RequestBody byte[] imageData,
            @Parameter(description = "文件名", required = true)
            @RequestParam("fileName") String fileName,
            @Parameter(description = "内容类型", required = true)
            @RequestParam("contentType") String contentType) {
        try {
            Long userId = getCurrentUserId();
            
            // 记录接收到的数据信息
            log.debug("接收到头像上传请求 - 用户ID: {}, 文件名: {}, 内容类型: {}, 数据大小: {} bytes", 
                     userId, fileName, contentType, imageData.length);
            
            // 如果数据大小很小，可能是Base64编码
            if (imageData.length < 1000) {
                log.debug("数据大小较小，前几个字节: {}", 
                         new String(imageData, 0, Math.min(50, imageData.length)));
            }
            
            String avatarUrl = avatarService.uploadAvatar(userId, imageData, fileName, contentType);
            
            return ResponseEntity.ok(ApiResponse.success("头像上传成功", 
                Map.of("avatarUrl", avatarUrl)));
        } catch (IllegalArgumentException e) {
            log.warn("头像上传失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        } catch (IOException e) {
            log.error("头像处理失败", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("头像处理失败"));
        } catch (Exception e) {
            log.error("头像上传异常", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("头像上传失败"));
        }
    }/**
     * 为指定用户上传头像 (管理员功能)
     */
    @RequireAuth
    @PostMapping("/upload/{userId}")
    @Operation(summary = "为指定用户上传头像", description = "管理员为指定用户上传头像")
    @SecurityRequirement(name = "Bearer Authentication")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Map<String, String>>> uploadAvatarForUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Long userId,
            @Parameter(description = "头像图片数据", required = true)
            @RequestParam("imageData") byte[] imageData,
            @Parameter(description = "文件名", required = true)
            @RequestParam("fileName") String fileName,
            @Parameter(description = "内容类型", required = true)
            @RequestParam("contentType") String contentType) {
        try {
            String avatarUrl = avatarService.uploadAvatar(userId, imageData, fileName, contentType);
            
            return ResponseEntity.ok(ApiResponse.success("头像上传成功", 
                Map.of("avatarUrl", avatarUrl)));
        } catch (IllegalArgumentException e) {
            log.warn("头像上传失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        } catch (IOException e) {
            log.error("头像处理失败", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("头像处理失败"));
        } catch (Exception e) {
            log.error("头像上传异常", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("头像上传失败"));
        }
    }
    
    /**
     * 使用 MultipartFile 上传头像 (推荐方式)
     */
    @RequireAuth
    @PostMapping("/upload-file")
    @Operation(summary = "使用MultipartFile上传用户头像", description = "推荐的头像上传方式，直接处理文件")
    @SecurityRequirement(name = "Bearer Authentication")
    public ResponseEntity<ApiResponse<Map<String, String>>> uploadAvatarFile(
            @Parameter(description = "头像文件", required = true)
            @RequestParam("file") MultipartFile file) {
        try {
            Long userId = getCurrentUserId();
            
            // 验证文件
            if (file.isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(ApiResponse.error("文件不能为空"));
            }
            
            // 获取文件信息
            String fileName = file.getOriginalFilename();
            String contentType = file.getContentType();
            byte[] imageData = file.getBytes();
            
            log.debug("接收到MultipartFile头像上传请求 - 用户ID: {}, 文件名: {}, 内容类型: {}, 数据大小: {} bytes", 
                     userId, fileName, contentType, imageData.length);
            
            String avatarUrl = avatarService.uploadAvatar(userId, imageData, fileName, contentType);
            
            return ResponseEntity.ok(ApiResponse.success("头像上传成功", 
                Map.of("avatarUrl", avatarUrl)));
        } catch (IllegalArgumentException e) {
            log.warn("头像上传失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getMessage()));
        } catch (IOException e) {
            log.error("头像处理失败", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("头像处理失败"));
        } catch (Exception e) {
            log.error("头像上传异常", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("头像上传失败"));
        }
    }
    
    /**
     * 获取头像图片
     */
    @GetMapping("/{fileName}")
    @Operation(summary = "获取头像图片", description = "通过文件名获取头像图片")
    public ResponseEntity<Resource> getAvatar(
            @Parameter(description = "头像文件名", required = true)
            @PathVariable String fileName) {
        try {
            File avatarFile = avatarService.getAvatarFile(fileName);
            Resource resource = new FileSystemResource(avatarFile);
            
            // 获取文件的MIME类型
            String contentType = Files.probeContentType(avatarFile.toPath());
            if (contentType == null) {
                contentType = "image/jpeg"; // 默认类型
            }
            
            return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CACHE_CONTROL, "max-age=3600") // 缓存1小时
                .body(resource);
        } catch (IOException e) {
            log.warn("头像文件不存在: {}", fileName);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("获取头像失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取头像缩略图
     */
    @GetMapping("/thumbnail/{fileName}")
    @Operation(summary = "获取头像缩略图", description = "获取头像的小尺寸缩略图")
    public ResponseEntity<Resource> getAvatarThumbnail(
            @Parameter(description = "头像文件名", required = true)
            @PathVariable String fileName) {
        try {
            File thumbnailFile = avatarService.getAvatarThumbnail(fileName);
            Resource resource = new FileSystemResource(thumbnailFile);
            
            // 获取文件的MIME类型
            String contentType = Files.probeContentType(thumbnailFile.toPath());
            if (contentType == null) {
                contentType = "image/jpeg"; // 默认类型
            }
            
            return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CACHE_CONTROL, "max-age=7200") // 缓存2小时
                .body(resource);
        } catch (IOException e) {
            log.warn("头像缩略图不存在: {}", fileName);
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("获取头像缩略图失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 删除头像
     */
    @RequireAuth
    @DeleteMapping("/delete")
    @Operation(summary = "删除用户头像", description = "删除当前用户的头像")
    @SecurityRequirement(name = "Bearer Authentication")
    public ResponseEntity<ApiResponse<Void>> deleteAvatar() {
        try {
            Long userId = getCurrentUserId();
            avatarService.deleteAvatar(userId);
            
            return ResponseEntity.ok(ApiResponse.success("头像删除成功", null));
        } catch (Exception e) {
            log.error("删除头像失败", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("删除头像失败"));
        }
    }
      /**
     * 删除指定用户头像 (管理员功能)
     */
    @RequireAuth
    @DeleteMapping("/delete/{userId}")
    @Operation(summary = "删除指定用户头像", description = "管理员删除指定用户的头像")
    @SecurityRequirement(name = "Bearer Authentication")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteAvatarForUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Long userId) {
        try {
            avatarService.deleteAvatar(userId);
            
            return ResponseEntity.ok(ApiResponse.success("头像删除成功", null));
        } catch (Exception e) {
            log.error("删除头像失败", e);
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("删除头像失败"));
        }
    }
      /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            return ((User) authentication.getPrincipal()).getId();
        }
        throw new RuntimeException("未找到当前用户信息");
    }
}
